# -*- coding=utf-8 -*-

import time
import json
import hashlib
import urllib
# import urllib2
import urllib.request
import urllib.parse


class Request:
    method = ''
    bizContent = ''

    def setBizContent(self, bizContent):
        if type(bizContent) is dict or type(bizContent) is list:
            self.bizContent = json.dumps(bizContent, separators=(',', ':'))
        else:
            self.bizContent = bytes(bizContent)

    def getBizContent(self):
        return self.bizContent

    def setMethod(self, method):
        self.method = method
        return self

    def getMethod(self):
        return self.method


class Client:
    appId = ''
    timestamp = ''
    version = ''
    signType = ''
    secretKey = ''

    def __init__(self):
        self.timestamp = int(round(time.time() * 1000))  # bytes(int(time.mktime(time.time())))
        self.version = '1.0'
        self.signType = 'md5'

    def setAppId(self, appId):
        self.appId = appId

    def setSecretKey(self, secretKey):
        self.secretKey = secretKey

    def setSignType(self, signType):
        self.signType = signType

    def setVersion(self, version):
        self.version = version

    def setTimestamp(self, timestamp):
        self.timestamp = bytes(timestamp)

    def createSignature(self, data, secretKey):
        list = []
        for k in sorted(data):
            list02 = [k, data[k]];
            # print("=".join('%s' %id for id in list02))
            # str02 = '='.json('%s' %id for id in list02)
            list.append("=".join('%s' % id for id in list02))
        list.append('key=' + secretKey)
        return hashlib.md5('&'.join(list).encode("utf-8")).hexdigest().upper()

    def execute(self, request):
        post = {}
        post['app_id'] = self.appId
        post['version'] = self.version
        post['timestamp'] = self.timestamp
        post['biz_content'] = request.getBizContent()
        post['method'] = request.getMethod()
        post['sign_type'] = self.signType
        post['sign'] = self.createSignature(data=post, secretKey=self.secretKey)
        headers = {
            'User-Agent': 'Mozilla 5.0 Python-SMS-SDK v1.0.0 (Haowei tech)'
        }
        # data = urllib.urlencode(post)
        data = urllib.parse.urlencode(post)
        data = data.encode('utf-8')

        # request = urllib2.Request('http://api.shansuma.com/gateway.do', data=data, headers=headers)
        request = urllib.request.Request('http://api.shansuma.com/gateway.do')
        f = urllib.request.urlopen(request, data)
        return f.read().decode('utf-8')
        # return urllib2.urlopen(request).read().decode('utf8')


def send(mobile: list, code: int):
    req = Request()
    req.setMethod(method='sms.message.send')
    req.setBizContent(bizContent={
        'mobile': mobile,  # 接受号码
        'sign': '内蒙古环境产权交易平台',  # 已通过审核的签名内容，这里不加签名id
        'send_time': '',
        'type': 0,
        'template_id': 'ST_2019043000000001',  # 已通过审核的模板id
        'params': {
            'code': code
        }
    })

    client = Client()
    client.setAppId('hw_11806')  # 在【设置】-开发设置中获取
    client.setSecretKey('3348992db04be759e90ccd4d0bce4689')  # 在【设置】-开发设置中获取
    client.setVersion('1.0')
    res = client.execute(req)
    return res


if __name__ == '__main__':
    req = Request()
    req.setMethod(method='sms.message.send')
    req.setBizContent(bizContent={
        'mobile': ['17611406668'],  # 接受号码
        'sign': '短信测试专用',  # 已通过审核的签名内容，这里不加签名id
        'send_time': '',
        'type': 0,
        'template_id': 'ST_2019043000000001',  # 已通过审核的模板id
        'params': {
            'code': 1569
        }
    })

    client = Client()
    client.setAppId('hw_11806')  # 在【设置】-开发设置中获取
    client.setSecretKey('3348992db04be759e90ccd4d0bce4689')  # 在【设置】-开发设置中获取
    client.setVersion('1.0')
    res = client.execute(req)
    print(res)
